package it.tcm.TeacherClassMate.writer;

import it.tcm.TeacherClassMate.beans.DisequationBean;
import it.tcm.TeacherClassMate.facade.DisequationManageBase;
import it.tcm.TeacherClassMate.form.DisequationUploadForm;
import it.tcm.TeacherClassMate.persistent.DBConnection;
import it.tcm.TeacherClassMate.util.DocxToHtmlMaker;
import it.tcm.TeacherClassMate.util.ResultToHtmlMaker;
import it.tcm.TeacherClassMate.util.Util;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

import org.apache.log4j.Logger;


public class DisequationBeanWriter {
	
	
	private String base = null;
	private JAXBContext contextObj = null;
	private Marshaller marshallerObj = null;
	
	
	private DisequationBeanWriter(String base) {
		this.base = base;
		 try{		
		   contextObj = JAXBContext.newInstance(org.docx4j.math.CTOMathPara.class);
		   marshallerObj = contextObj.createMarshaller();
		   marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);	
		 } catch (Exception e) {
			 
		 }
	}
	
    private static volatile DisequationBeanWriter instance = null;
	
	public static DisequationBeanWriter getInstance(String base) {
        if (instance == null) {
                synchronized (DisequationBeanWriter .class){
                        if (instance == null) {
                                instance = new DisequationBeanWriter (base);
                        }
              }
        }
        return instance;
    }
	
	private Logger logger = Logger.getLogger(this.getClass().getName());
	
	public boolean insertDisequation(DisequationUploadForm form,boolean blobFlag,Integer typologyId)  {
	
	  Connection  conn = null;
	
	  try{
		  
		  JAXBContext contextObj = JAXBContext.newInstance(org.docx4j.math.CTOMathPara.class);
		  Marshaller marshallerObj = contextObj.createMarshaller();
		  marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);		
	
		  DBConnection db = new DBConnection();
		  conn = db.getDBConnection();
		   
		  Context ctx = new InitialContext();
		  String docxFileDir = (String)ctx.lookup("java:comp/env/docxPath");
		  
		  DisequationManageBase emb = new DisequationManageBase();
		  
		  String disequationDocxFileDir = docxFileDir + "//D//";
		  
		  // create directory if not
		  File dir = new File(disequationDocxFileDir);
		  if (!dir.exists()) {
			  	new File(disequationDocxFileDir).mkdir();
		  }
		  		     
	      DisequationBean diseequationBean = new DisequationBean();
	      diseequationBean.setTypologyId(typologyId);
	      diseequationBean.setType(Util.DISEQUATION);    
	      diseequationBean.setCoefficienti(form.getCoefficienti());
	      diseequationBean.setDifficolta(Integer.valueOf(form.getDifficolta()));
	      diseequationBean.setPrefix(Util.DISEQUATION_PREFIX);	     
	      diseequationBean.setEsponenziale(form.getEsponenziale());   
	      diseequationBean.setFormaNormale(form.getFormanormale());
	      diseequationBean.setSistema(form.getSistema());
	      diseequationBean.setFratta(form.getFratta());	   
	      diseequationBean.setGrado(Integer.valueOf(form.getGrado()));
	      diseequationBean.setIrrazionale(form.getIrrazionale() );
	      diseequationBean.setLogaritmica(form.getLogaritmica());
	      diseequationBean.setResultString(form.getResultstring());
	      emb.save(diseequationBean);
	      form.setId(diseequationBean.getId());
	      
	      String filedocxfilename = disequationDocxFileDir + Util.DISEQUATION_PREFIX + diseequationBean.getId().toString() + ".docx";
		  logger.info("filedocxfilename " + disequationDocxFileDir + Util.DISEQUATION_PREFIX + diseequationBean.getId().toString() + ".docx");	
		  String filehtmfilename = disequationDocxFileDir + Util.DISEQUATION_PREFIX + diseequationBean.getId().toString() + ".htm";
		  logger.info("filehtmfilename " + disequationDocxFileDir + Util.DISEQUATION_PREFIX + diseequationBean.getId().toString() + ".htm");	
		  File filedocx = Util.bytesToFile(filedocxfilename, form.getDocx().getFileData());
		  logger.info("form.getDocx().getFileSize() " + form.getDocx().getFileSize());	
		  File filehtm = DocxToHtmlMaker.getDocxToHtmlMaker().make(marshallerObj, filedocx, filedocxfilename, filehtmfilename, disequationDocxFileDir,diseequationBean.getId().toString(),base);
		  File fileresult = null;
		  File fileresulthtm = null;
		  String fileresultdocxfilename = disequationDocxFileDir + Util.DISEQUATION_PREFIX + diseequationBean.getId().toString() + "_result.docx";
		  String fileresulthtmfilename = disequationDocxFileDir + Util.DISEQUATION_PREFIX + diseequationBean.getId().toString() + "_result.htm";  
		  if ( diseequationBean.getResultString() == null || diseequationBean.getResultString().trim().equals("")) {		  
			  logger.info("form.getResult().getFileSize() " + form.getResult().getFileSize());				
			  fileresult = Util.bytesToFile(fileresultdocxfilename, form.getResult().getFileData());
			  fileresulthtm = DocxToHtmlMaker.getDocxToHtmlMaker().make(marshallerObj, fileresult, fileresultdocxfilename, fileresulthtmfilename, disequationDocxFileDir,diseequationBean.getId().toString(),base);		
		  } else {
			  // creo file per il risultato
			  ResultToHtmlMaker resultmaker = new ResultToHtmlMaker();
			  fileresult = resultmaker.create(diseequationBean.getResultString(), fileresult, fileresultdocxfilename);
			  fileresulthtm = resultmaker.make(fileresult,fileresulthtmfilename);
		  }
		  if (blobFlag) {
	
			    String sql = "UPDATE DISEQUATION SET docx = ?, image = ?, result = ?, result_image = ? WHERE id = ?";
			    PreparedStatement stmt0 = conn.prepareStatement(sql);
			    
			    stmt0.setInt(5, diseequationBean.getId());
			    	
			    logger.info("filedocxoutput.length()" + filedocx.length());
			    FileInputStream fisdocx = new FileInputStream(filedocx);	    		    	   
			    stmt0.setBinaryStream(1, fisdocx, (int) filedocx.length()); // metto il docx	
			    
			    logger.info("image.length()" + filehtm.length());
			    FileInputStream fisimage = new FileInputStream(filehtm);	    		    	   
			    stmt0.setBinaryStream(2, fisimage, (int) filehtm.length()); // metto html del docx
			    
			    logger.info("fileresult.length()" + fileresult.length());
			    FileInputStream fisresult = new FileInputStream(fileresult);	    		    	   
			    stmt0.setBinaryStream(3, fisresult, (int) fileresult.length()); // metto il result	
			    
			    logger.info("result_image.length()" + fileresulthtm.length());
			    FileInputStream fisresult_image = new FileInputStream(fileresulthtm);	    		    	   
			    stmt0.setBinaryStream(4, fisresult_image, (int) fileresulthtm.length()); // metto html del result
			    		    
			    stmt0.execute();				    
			    fisdocx.close();
			    fisimage.close();
			    fisresult.close();
			    fisresult_image.close();
    
		  }
		    
	  } catch (Throwable e) {
		    logger.error("Exception " + e.getMessage());  
		    e.printStackTrace();
		    return false;
	  } finally {
		  try {
			    conn.close();
		  } catch (SQLException e) {
			  e.printStackTrace();
	      }
	 }
	  
	 return true;
	  
   }

}
